<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\AdminController;
use Illuminate\Http\Request;
use App\Models\Order;
use App\Models\LevelOrder;

class Bill extends AdminController{
    
    public function index(Request $req){
        $psize = 30;
        $starttime = $req->post('startTime',date('Y-m-d',strtotime('-7 day')));
        $endtime = $req->post('endTime',date('Y-m-d'));
        if($req->method() == 'POST'){
            $endtime .= " 23:59:59";
            $status = $req->post('status',0);
            
            if ($req->post('op') == 'stat') {
                $list = Order::selectRaw("sum(price) as price,sum(costprice) as costprice,sum(reback+preback) as reback")->where('status','>',0)->where('createtime','>=',strtotime($starttime))->where('createtime','<=',strtotime($endtime));
                $ulist = LevelOrder::selectRaw("sum(price) as price,0 as costprice,sum(reback) as reback")->where('status','>',0)->where('createtime','>=',strtotime($starttime))->where('createtime','<=',strtotime($endtime));
                if ($status == 0){
                    $list->union($ulist);
                    $list = Order::from($list)->selectRaw("sum(price) as price,sum(costprice) as costprice,sum(reback) as reback");
                }elseif ($status == 2) $list = $ulist;
                $data = $list->first();
                $stat = [round($data->price,2)];
                $stat[] = round($data->price * 0.006,2);
                $stat[] = $data->costprice;
                $stat[] = round($data->reback,2);
                $stat[] = round($data->price - $stat[1] - $data->costprice - $data->reback,2);
                wxresp(1,['stat'=>$stat]);
            }
            
            $list = Order::select("ordersn","type","price","costprice","reback","preback","createtime")->where('status','>',0)->where('createtime','>=',strtotime($starttime))->where('createtime','<=',strtotime($endtime));
            $ulist = LevelOrder::selectRaw("ordersn,'level' as type,price,0 as costprice,reback,0 as preback,createtime")->where('status','>',0)->where('createtime','>=',strtotime($starttime))->where('createtime','<=',strtotime($endtime));
            if ($status == 0) $list->union($ulist);
            elseif ($status == 2) $list = $ulist;
            $list = $list->orderByDesc('createtime')->paginate($psize);
            foreach ($list as &$v) {
                $v->createtime = date('Y-m-d H:i',$v->createtime);
                $v->fee = round($v->price * 0.006,2);
                $v->profile = round($v->price - $v->fee - $v->reback - $v->costprice - $v->preback,2);
                $v->reback = round($v->preback + $v->reback,2);
            }
            $data = ['rows' => $list->items(), 'total' => $list->total()];
            wxresp(1, $data);
        }
        return $this->V("index",array('startTime'=>$starttime,'endTime'=>$endtime));
    }
}